package api

import (
	"fmt"
	global2 "longmen/server/config/global"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/grpc_client"
	pb "longmen/server/pkg/protobuf"
	"strconv"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/spf13/cast"
	"google.golang.org/grpc/status"
)

// @Summary 腾讯im登陆获取凭证
// @Description 腾讯im登陆获取凭证
// @Accept  json
// @Produce  json
// @Tags tencentIm
// @Success 200 {object} protobuf.UserSigResp "result"
// @Router /api/tencentIm/getUserSig [POST]
func (base Controller) GetUserSig(c echo.Context) error {
	r := &pb.UserSigReq{}
	iId := cast.ToInt(c.Get("uid"))
	if iId > 0 {
		r.Id = cast.ToString(iId)
	} else {
		deviceInfo := c.Request().Header.Get("device-info")
		if len(deviceInfo) > 0 {
			r.Id = cast.ToString(util.HashUid(deviceInfo)) //根据device Id生成数字哈希同一个deviceId生成的会一样
		}
	}
	//sAuth := c.Request().Header.Get("authoriation") + c.Request().Header.Get("Authoriation")
	//global.Log.Infof("authoriation:%s", sAuth)
	//global.Log.Infof("GetUserSig:%v", r)
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcTencentImClient.GetUserSig(ctx, r)
	if err != nil {
		return util.BuildFail(c, _const.RPC_FAILED, status.Convert(err).Message(), err)
	}
	return util.BuildSuccess(c, resp, _const.EMPTY_STR)
}

type CallbackResp struct {
	ActionStatus    string                  `json:"ActionStatus"`
	ErrorInfo       string                  `json:"ErrorInfo"`
	ErrorCode       uint32                  `json:"ErrorCode"`
	MsgBody         []*CallbackResp_Msgbody `json:"MsgBody,omitempty"`
	CloudCustomData string                  `json:"CloudCustomData,omitempty"`
}
type CallbackResp_Msgbody struct {
	MsgType    string                   `json:"MsgType"`
	MsgContent *CallbackResp_Msgcontent `json:"MsgContent"`
}
type CallbackResp_Msgcontent struct {
	Text string `json:"Text"`
	Data string `json:"Data"`
	Ext  string `json:"Ext"`
}

type OfflinePushSetting struct {
	Uid         int64 `json:"uid"`
	RemindMatch int8  `json:"remindMatch"` //0开启 1关闭
	RemindLive  int8  `json:"remindLive"`  //0开启 1关闭
}

type CallBackParam struct {
	SdkAppid        string `json:"SdkAppid"`
	CallbackCommand string `json:"CallbackCommand"`
	contenttype     string `json:"contenttype"`
	ClientIP        string `json:"ClientIP"`
	OptPlatform     string `json:"OptPlatform"`
}

// 回調用

// @Summary TIM回调接口
// @Description TIM回调接口
// @Accept  json
// @Produce  json
// @Tags Noble
// @Param   sendBody body protobuf.CallbackReq true "body"
// @Router /api/tencentIm/callback [POST]
func (base Controller) Callback(c echo.Context) error {
	r := &pb.CallbackReq{}
	rayStr := c.Get("body").(string)
	//global.Log.Debugf("原始数据 :%v", rayStr)
	if err := util.Json2Struct(rayStr, r); err != nil {
		global2.Log.Errorf("Callback Unmarshal Erro : %v", err)
		return util.BadParam(c, err)
	}
	result := &CallbackResp{}
	if strings.ToLower(r.From_Account) == "admin" {
		result.ErrorCode = 0
		result.ErrorInfo = ""
		result.ActionStatus = "OK"
		return c.JSON(200, result)
	}
	global2.Log.Debugf("From_Account :%v", r.From_Account)
	r.ClientIP = c.FormValue("ClientIP")
	r.OptPlatform = c.FormValue("OptPlatform")
	ctx, cancel := base.GrpcWithTimeout()
	defer cancel()
	resp, err := grpc_client.GrpcTencentImClient.Callback(ctx, r)
	if err != nil {
		result.ErrorCode = 10199
		result.ErrorInfo = err.Error()
		result.ActionStatus = "OK"
		global2.Log.Errorf("%v-%v-%v", err, r.GetMsgBody(), time.Now())
		return c.JSON(200, result)
	}

	//copier.Copy(result, resp)
	return c.JSON(200, resp)
}

// todo 待完善
func (base Controller) SetOfflinePush(c echo.Context) error {
	r := &OfflinePushSetting{}
	b := c.Get("body").(string)
	if err := util.Json2Struct(b, r); err != nil {
		global2.Log.Errorf("SetOfflinePush Unmarshal Erro : %v", err)
		return util.BadParam(c, err)
	}

	userInfo := &models_main.UserInfo{}

	global2.GetR().Where("uid = ?", r.Uid).First(userInfo)

	if userInfo.RemindMatch != r.RemindMatch {
		if r.RemindMatch == 0 {
			imsdk2.GetSdk().AddTags([]string{strconv.FormatInt(r.Uid, 10)}, []string{imsdk2.NOTIFY_START_MATCH})
		} else {
			imsdk2.GetSdk().DeleteTags([]string{strconv.FormatInt(r.Uid, 10)}, []string{imsdk2.NOTIFY_START_MATCH})
		}
	}

	if userInfo.RemindLive != r.RemindLive {
		if r.RemindLive == 0 {
			imsdk2.GetSdk().AddTags([]string{strconv.FormatInt(r.Uid, 10)}, []string{imsdk2.NOTIFY_START_LIVE})
		} else {
			imsdk2.GetSdk().DeleteTags([]string{strconv.FormatInt(r.Uid, 10)}, []string{imsdk2.NOTIFY_START_LIVE})
		}
	}

	userInfo.RemindLive = r.RemindLive
	userInfo.RemindMatch = r.RemindMatch
	if userInfo.Uid == 0 {
		userInfo.Uid = uint(r.Uid)
		global2.GetR().Where("uid = ?", r.Uid).Save(userInfo)
		return util.BuildSuccess(c, nil, _const.EMPTY_STR)
	}
	//global.GetR().Where("uid = ?", r.Uid).Updates(userInfo)
	global2.GetR().Where("uid = ?", r.Uid).Save(&userInfo)
	return util.BuildSuccess(c, nil, _const.EMPTY_STR)
}

func (base Controller) GetOfflinePush(c echo.Context) error {
	r := &OfflinePushSetting{}
	b := c.Get("body").(string)
	if err := util.Json2Struct(b, r); err != nil {
		global2.Log.Errorf("GetOfflinePush Unmarshal Erro : %v", err)
		return util.BadParam(c, err)
	}
	if r.Uid == 0 {
		return util.BadParam(c, fmt.Errorf("uid is null"))
	}

	userInfo := &models_main.UserInfo{}
	global2.GetR().Where("uid = ?", r.Uid).First(userInfo)

	r.RemindLive = userInfo.RemindLive
	r.RemindMatch = userInfo.RemindMatch

	return util.BuildSuccess(c, r, _const.EMPTY_STR)
}
